<template>
  <view class="subscription-container">
    <!-- 支付组件测试 -->
    <payment 
      :payMode="payMode" 
      :pay_close="pay_close" 
      :is-call="true" 
      :order_id="orderId"
      :totalPrice="totalPrice"
      @onChangeFun="onChangeFun">
    </payment>
    
    <!-- 顶部状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="page-title">会员套餐</view>
      <view class="placeholder-btn"></view>
    </view>
    
    <!-- 免费试用提醒 -->
    <view class="free-trial-alert">
      <text class="alert-icon">ⓘ</text>
      <view class="alert-content">
        <text>免费试用已结束</text>
        <text class="alert-desc">您已使用5次免费试用，请选择套餐升级使用更多功能</text>
      </view>
    </view>
    
    <!-- 会员特权 -->
    <view class="vip-features">
      <view class="features-title">会员专享权益</view>
      <view class="features-grid">
        <view class="feature-item">
          <text class="feature-icon">👕</text>
          <text class="feature-name">服装穿搭推荐</text>
          <text class="feature-desc">根据您的信息定制穿搭推荐</text>
        </view>
        <view class="feature-item">
          <text class="feature-icon">📅</text>
          <text class="feature-name">历史记录保存</text>
          <text class="feature-desc">所有穿搭方案永久保存</text>
        </view>
        <view class="feature-item">
          <text class="feature-icon">📊</text>
          <text class="feature-name">精准风格分析</text>
          <text class="feature-desc">专业穿搭建议与时尚指南</text>
        </view>
        <view class="feature-item">
          <text class="feature-icon">🛍️</text>
          <text class="feature-name">优惠购物推荐</text>
          <text class="feature-desc">独家优品品牌推荐</text>
        </view>
      </view>
    </view>
    
    <!-- 会员套餐列表 -->
    <view class="subscription-options">
      <!-- 小额转化包 -->
      <view class="subscription-option" :class="{ 'active': selectedPlan === 'micro' }" @click="selectPlan('micro')">
        <view class="option-radio">
          <view class="radio-inner" v-if="selectedPlan === 'micro'"></view>
        </view>
        <view class="option-content">
          <view class="option-title">
            <text>小额转化包</text>
            <text class="option-price">¥9.9</text>
          </view>
          <text class="option-desc">5次使用</text>
          <text class="option-compare">单次仅需¥1.98，相当经济实惠</text>
        </view>
        <view class="recommended-tag" v-if="selectedPlan === 'micro'">推荐购买</view>
      </view>
      
      <!-- 中阶套餐 -->
      <view class="subscription-option" :class="{ 'active': selectedPlan === 'medium' }" @click="selectPlan('medium')">
        <view class="option-radio">
          <view class="radio-inner" v-if="selectedPlan === 'medium'"></view>
        </view>
        <view class="option-content">
          <view class="option-title">
            <text>中阶套餐</text>
            <text class="option-price">¥14.9</text>
          </view>
          <text class="option-desc">10次使用</text>
          <text class="option-compare">单次仅需¥1.49，特惠12次</text>
        </view>
      </view>
      
      <!-- 高级包 -->
      <view class="subscription-option" :class="{ 'active': selectedPlan === 'premium' }" @click="selectPlan('premium')">
        <view class="option-radio">
          <view class="radio-inner" v-if="selectedPlan === 'premium'"></view>
        </view>
        <view class="option-content">
          <view class="option-title">
            <text>高级包</text>
            <text class="option-price">¥24.9</text>
          </view>
          <text class="option-desc">20次使用</text>
          <text class="option-compare">单次仅需¥1.25，赠送用户画像</text>
        </view>
      </view>
      
      <!-- 活动特惠包 -->
      <view class="subscription-option" :class="{ 'active': selectedPlan === 'special' }" @click="selectPlan('special')">
        <view class="option-radio">
          <view class="radio-inner" v-if="selectedPlan === 'special'"></view>
        </view>
        <view class="option-content">
          <view class="option-title">
            <text>活动特惠包</text>
            <text class="option-price">¥9.9</text>
          </view>
          <text class="option-desc">8次使用 限时24小时</text>
          <text class="option-compare">单次仅需¥1.24，超值优惠</text>
        </view>
        <view class="limited-tag">限时特惠</view>
      </view>
    </view>
    
    <!-- 支付方式 -->
    <view class="payment-methods">
      <view class="section-title">支付方式</view>
      <view class="payment-option" :class="{ 'active': paymentMethod === 'wechat' }" @click="selectPayment('wechat')">
        <view class="payment-icon wechat-icon">
          <text class="payment-emoji">💳</text>
        </view>
        <text class="payment-name">微信支付</text>
        <view class="option-radio">
          <view class="radio-inner" v-if="paymentMethod === 'wechat'"></view>
        </view>
      </view>
      
      <view class="payment-option" :class="{ 'active': paymentMethod === 'alipay' }" @click="selectPayment('alipay')">
        <view class="payment-icon alipay-icon">
          <text class="payment-emoji">💳</text>
        </view>
        <text class="payment-name">支付宝</text>
        <view class="option-radio">
          <view class="radio-inner" v-if="paymentMethod === 'alipay'"></view>
        </view>
      </view>
    </view>
    
    <!-- 用户协议同意 -->
    <view class="agreement-checkbox">
      <view class="checkbox" :class="{ 'checked': agreeToTerms }" @click="toggleAgreement"></view>
      <text class="agreement-text">我已阅读并同意<text class="highlight">《用户服务协议》</text>和<text class="highlight">《隐私政策》</text></text>
    </view>
    
    <!-- 底部支付按钮 -->
    <view class="pay-button-container">
      <button class="pay-button" @click="processPayment">
        立即支付 ¥{{getSelectedPrice()}}
      </button>
    </view>
  </view>
</template>

<script>
import {wechatAuthV2} from '@/api/public';
import payment from '@/components/payment/index.vue';
import { orderPay } from '@/api/order.js';

export default {
  components: {
    payment
  },
  data() {
    return {
      statusBarHeight: 20,
      selectedPlan: 'micro', // 默认选中小额转化包
      paymentMethod: 'wechat', // 默认微信支付
      agreeToTerms: false, // 默认未勾选协议
      // 套餐价格
      planPrices: {
        micro: 9.9,
        medium: 14.9,
        premium: 24.9,
        special: 9.9
      },
      // 支付组件参数
      pay_close: false,
      payMode: [{
        name: '微信支付',
        icon: 'icon-weixinzhifu',
        value: 'weixin',
        title: '微信支付',
        payStatus: true
      },
      {
        name: '支付宝支付',
        icon: 'icon-zhifubao',
        value: 'alipay',
        title: '支付宝支付',
        payStatus: true
      },
      {
        name: '余额支付',
        icon: 'icon-qiandai',
        value: 'yue',
        title: '余额支付',
        payStatus: true,
        number: 0 // 用户余额
      }],
      totalPrice: '9.9',
      orderId: '' // 订单ID
    };
  },
  onLoad() {
    this.getSystemInfo();
  },
  methods: {
    // 测试支付组件
    testPayment() {
      this.pay_close = true;
    },
    
    // 支付回调处理
    onChangeFun(e) {
      console.log('支付回调:', e);
      let action = e.action || null;
      let value = e.value != undefined ? e.value : null;
      
      if (action === 'payClose') {
        this.pay_close = false;
      } else if (action === 'payCheck') {
        // 调用支付接口
        console.log('支付类型:', value);
        uni.showToast({
          title: '调用支付接口: ' + value,
          icon: 'none'
        });
        
        // 模拟支付过程
        setTimeout(() => {
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });
          this.pay_close = false;
        }, 1500);
      }
    },
    
    getSystemInfo() {
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight || 20;
      // #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
      const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
      this.statusBarHeight = menuButtonInfo.top;
      // #endif
    },
    
    selectPlan(plan) {
      this.selectedPlan = plan;
      this.totalPrice = this.planPrices[plan].toString();
    },
    
    selectPayment(method) {
      this.paymentMethod = method;
    },
    
    toggleAgreement() {
      this.agreeToTerms = !this.agreeToTerms;
    },
    
    getSelectedPrice() {
      return this.planPrices[this.selectedPlan];
    },
    
    processPayment() {
      if (!this.agreeToTerms) {
        uni.showToast({
          title: '请先同意用户协议',
          icon: 'none'
        });
        return;
      }

      // 显示加载提示
      uni.showLoading({
        title: '支付处理中'
      });
      
      // 1. 添加购物车
      this.addToCart();
    },
    
    // 添加购物车
    addToCart() {
      uni.request({
        url: 'https://test.zysemtime.com/api/cart/add',
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('LOGIN_STATUS_TOKEN')
        },
        data: {
          productId: 77,     // 商品ID
          cartNum: 1,    
          uniqueId: "",  
          new: 1,       
          combinationId: 0,  
          secKillId: 0,     
          bargainId: 0,     
          advanceId: 0,
          noAuth: "true"
        },
        success: (res) => {
          console.log('添加购物车成功:', res);
          if (res.data && res.data.data && res.data.data.cartId) {
            this.orderConfirm(res.data.data.cartId);
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '添加购物车失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('添加购物车失败:', err);
          uni.hideLoading();
          uni.showToast({
            title: '添加购物车失败',
            icon: 'none'
          });
        }
      });
    },
    //订单确认
    orderConfirm(cartId){
      console.log('cartId:', cartId);
      console.log('token:', uni.getStorageSync('token'));
      
      uni.request({
        url: 'https://test.zysemtime.com/api/order/confirm',
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('LOGIN_STATUS_TOKEN')
        },
        data: {
          cartId : cartId,
          new: 1,
          addressId: 0,
          shipping_type: 1
        },
        success: (res) => {
          console.log('订单确认成功:', res);
          this.createOrder(res.data.data.orderKey);
        },
        fail: (err) => {
          console.error('订单确认失败:', err);
        }
      });
    },
    
    // 创建订单
    createOrder(orderkey) {
      console.log('orderkey:', orderkey);
//       uni.login({
//          provider: 'weixin',
//          success: (loginRes) => {
//            wechatAuthV2(loginRes.code, null).then(res => {
//            // res.data 里通常会有 openid、token 或用户信息
//            console.log(res.data);
//     });
//   }
// });
      uni.request({
        url: 'https://test.zysemtime.com/api/order/create/' + orderkey,
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + uni.getStorageSync('LOGIN_STATUS_TOKEN')
        },
        data: {
          payType: this.paymentMethod === 'wechat' ? 'weixin' : 'alipay',
          shipping_type: 1,
          product_id: 1,
          num: 1,
          unique: Date.now(),
          openid: uni.getStorageSync('uid') || ''
        },
        success: (res) => {
          console.log('创建订单成功:', res);
          console.log('orderId:', res.data.data.result.orderId);
          
          if (res.data && res.data.data.result.orderId) {
            this.orderId = res.data.data.result.orderId;
            // 使用orderPay函数发起支付
            this.callPayment(res.data.data.result.orderId);
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '创建订单失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('创建订单失败:', err);
          uni.hideLoading();
          uni.showToast({
            title: '创建订单失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 使用order.js中的orderPay函数调用支付
    callPayment(orderId) {
      const paytype = this.paymentMethod === 'wechat' ? 'weixin' : 'alipay';
      console.log('orderId:', orderId);
      
      // 构建支付参数
      const payData = {
        uni: orderId,
        paytype: paytype,
        // #ifdef MP
        from: 'routine',
        // #endif
        // #ifdef H5
        from: 'weixinh5',
        // #endif
      };
      
      console.log('支付参数:', payData);
      
      // 调用orderPay API函数
      orderPay(payData).then(res => {
        uni.hideLoading();
        console.log('支付请求成功:', res);
        
        if (res.status === 200) {
          const jsConfig = res.data.result.jsConfig;
          
          // 微信小程序支付
          // #ifdef MP-WEIXIN
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: jsConfig.timestamp,
            nonceStr: jsConfig.nonceStr,
            package: jsConfig.package,
            signType: jsConfig.signType,
            paySign: jsConfig.paySign,
            success: (payRes) => {
              console.log('支付成功', payRes);
              this.handlePaymentSuccess();
            },
            fail: (err) => {
              console.log('支付失败', err);
              this.handlePaymentFailure(err.errMsg || '支付失败');
            }
          });
          // #endif
          
          // H5支付
          // #ifdef H5
          if (res.status === "WECHAT_H5_PAY") {
            // H5微信支付，直接跳转
            location.replace(jsConfig.h5_url);
          } else {
            // 其他H5支付方式
            uni.showToast({
              title: '暂不支持当前环境下的支付方式',
              icon: 'none'
            });
          }
          // #endif
        } else {
          this.handlePaymentFailure(res.msg || '支付请求失败');
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('支付请求失败:', err);
        this.handlePaymentFailure(typeof err === 'string' ? err : '支付请求失败');
      });
    },
    
    // 处理支付成功
    handlePaymentSuccess() {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            // 可以跳转到订单详情或其他页面
            uni.navigateBack();
          }, 2000);
        }
      });
    },
    
    // 处理支付失败
    handlePaymentFailure(message = '支付取消或失败') {
      uni.showToast({
        title: message,
        icon: 'none'
      });
    },

    // 获取使用次数
    getUsageCount() {
      const usageCounts = {
        micro: 5,
        medium: 10,
        premium: 20,
        special: 8
      };
      return usageCounts[this.selectedPlan] || 0;
    }, 
    
    goBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style lang="scss">
.subscription-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
  position: relative;
}

.status-bar {
  width: 100%;
  background-color: #fff;
}

.nav-header {
  height: 90rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  background-color: #fff;
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}

.page-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  text-align: center;
}

.placeholder-btn {
  width: 60rpx;
  height: 60rpx;
}

.free-trial-alert {
  margin: 30rpx;
  background: #fff0f0;
  border-radius: 12rpx;
  padding: 24rpx;
  display: flex;
  align-items: flex-start;
  border-left: 8rpx solid #ff4d6a;
}

.alert-icon {
  font-size: 32rpx;
  color: #ff4d6a;
  margin-right: 16rpx;
  font-weight: bold;
}

.alert-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.alert-desc {
  font-size: 24rpx;
  color: #888;
  margin-top: 6rpx;
}

.vip-features {
  margin: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.features-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
}

.features-grid {
  display: flex;
  flex-wrap: wrap;
}

.feature-item {
  width: 50%;
  padding: 20rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.feature-icon {
  font-size: 48rpx;
  margin-bottom: 16rpx;
}

.feature-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.feature-desc {
  font-size: 22rpx;
  color: #888;
  text-align: center;
  padding: 0 20rpx;
}

.subscription-options {
  margin: 30rpx;
}

.subscription-option {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.subscription-option.active {
  background: #fff9fc;
  border: 1rpx solid #ff4d6a;
}

.option-radio {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 1rpx solid #ddd;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.option-radio .radio-inner {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #ff4d6a;
}

.option-content {
  flex: 1;
}

.option-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
}

.option-price {
  color: #ff4d6a;
  font-size: 36rpx;
  font-weight: bold;
}

.option-desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.option-compare {
  font-size: 22rpx;
  color: #999;
}

.recommended-tag {
  position: absolute;
  top: 0;
  right: 0;
  padding: 6rpx 16rpx;
  background: #ff4d6a;
  color: #fff;
  font-size: 20rpx;
  border-radius: 0 12rpx 0 12rpx;
}

.limited-tag {
  position: absolute;
  top: 0;
  right: 0;
  padding: 6rpx 16rpx;
  background: #ff9500;
  color: #fff;
  font-size: 20rpx;
  border-radius: 0 12rpx 0 12rpx;
}

.payment-methods {
  margin: 30rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.payment-option {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.payment-option:last-child {
  border-bottom: none;
}

.payment-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10rpx;
}

.payment-emoji {
  font-size: 36rpx;
}

.wechat-icon {
  background-color: #07c160;
}

.alipay-icon {
  background-color: #1677ff;
}

.payment-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.agreement-checkbox {
  margin: 50rpx 30rpx 30rpx;
  display: flex;
  align-items: center;
}

.checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 1rpx solid #ddd;
  border-radius: 50%;
  margin-right: 16rpx;
  position: relative;
}

.checkbox.checked {
  background-color: #ff4d6a;
  border-color: #ff4d6a;
}

.checkbox.checked::after {
  content: '';
  position: absolute;
  left: 12rpx;
  top: 6rpx;
  width: 10rpx;
  height: 16rpx;
  border: solid #fff;
  border-width: 0 3rpx 3rpx 0;
  transform: rotate(45deg);
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
}

.highlight {
  color: #ff4d6a;
}

.pay-button-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 24rpx 30rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.pay-button {
  background: linear-gradient(to right, #ff6b9d, #ff4d7e);
  color: #fff;
  border-radius: 50rpx;
  font-size: 32rpx;
  padding: 20rpx 0;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  font-weight: 500;
  box-shadow: 0 6rpx 16rpx rgba(255, 77, 126, 0.25);
}
</style> 